JavaScript for Kids: A Playful Introduction to Programming by Nick Morgan
Try It Out!
You can speed up this animation by raising the amount that leftOffset is increased every time moveHeading is called or by reducing the time that setInterval waits between calls to moveHeading.
How would you double the speed that the heading moves? Try it with both techniques. What difference do you see?
Responding to User Actions
As you’ve seen, one way to control when code is run is with the functions setTimeout and setInterval, which run a function once a fixed amount of time has passed. Another way is to run code only when a user performs certain actions, such as clicking, typing, or even just moving the mouse. This will let users interact with your web page so that your page responds according to what they do.
In a browser, every time you perform an action such as clicking, typing, or moving your mouse, something called an event is triggered. An event is the browser’s way of saying, “This thing happened!” You can listen to these events by adding an event handler to the element where the event happened. Adding an event handler is your way of telling JavaScript, “If this event happens on this element, call this function.” For example, if you want a function to be called when the user clicks a heading element, you could add a click event handler to the heading element. We’ll look at how to do that next.
JavaScript for Kids: A Playful Introduction to Programming by Nick Morgan.azw3
JavaScript for Kids: A Playful Introduction to Programming by Nick Morgan.mobi
JavaScript for Kids: A Playful Introduction to Programming by Nick Morgan.pdf